package com.ocean.common.utils;

import com.github.pagehelper.util.StringUtil;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

/**
 * Created by Administrator on 2017/11/22 0022.
 */
public class ExecLinuxCMDUtils {
    static Logger log = LoggerFactory.getLogger(ExecLinuxCMDUtils.class);

    //需要执行的命令
    public static String exec(String cmd) {
        final StringBuffer info = new StringBuffer();
        final StringBuffer error = new StringBuffer();
        try {
            String[] cmdA = {"/bin/sh", "-c", cmd};
            //运行命令
            Process ps = Runtime.getRuntime().exec(cmdA);
            //未了防止缓存区满了导致进程阻塞 开两个线程 把进程的输入流和错误流读取出来
            //获取进程的标准输入流
            final InputStream is1 = ps.getInputStream();
            //获取进程的错误流
            final InputStream is2 = ps.getErrorStream();
            //启动两个线程，一个线程负责读标准输出流，
            new Thread() {
                public void run() {
                    BufferedReader br1 = new BufferedReader(new InputStreamReader(is1));
                    try {
                        String line1 = null;
                        while ((line1 = br1.readLine()) != null) {
                            if (line1 != null) {
                                info.append(line1).append("\n");
                            }
                        }
                    } catch (IOException e) {
                        log.error("IO异常", e);
                    } finally {
                        IOUtils.closeQuietly(br1);
                        IOUtils.closeQuietly(is1);
                    }
                }
            }.start();
            //另一个负责读标准错误流
            new Thread() {
                public void run() {
                    BufferedReader br2 = new BufferedReader(new InputStreamReader(is2));

                    try {
                        String line2 = null;
                        while ((line2 = br2.readLine()) != null) {
                            if (line2 != null) {
                                error.append(line2).append("\n");
                            }
                        }
                    } catch (IOException e) {
                        log.error("IO异常", e);
                    } finally {
                        IOUtils.closeQuietly(br2);
                        IOUtils.closeQuietly(is2);
                    }
                    log.error("命令执行错误内容{}", error.toString());
                }
            }.start();
            //等待子线程完成
            ps.waitFor();
            //销毁子线程
            ps.destroy();
        } catch (Exception e) {
            log.error("批处理中断异常", e);
        } finally {

        }
        if (StringUtil.isNotEmpty(info.toString())) {
            return info.toString();
        }
        else {
            return error.toString();
        }
    }
}
